package common.service.base.resolver;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.alibaba.fastjson.JSONObject;

import common.service.base.annotation.MobileRequestParam;
import common.service.base.common.ReqVo;
import common.service.base.handler.ThreadLocalHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName MobileRequestParamResolver
 * @Description Todo
 * @Author lixin
 * @Date 2020/02/10 下午3:12
 * Version 0.0.1
 **/
@Slf4j
public class MobileRequestParamResolver implements HandlerMethodArgumentResolver{

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Annotation[] parameterAnnotations =
                methodParameter.getParameterAnnotations();

        for (Annotation parameterAnnotation : parameterAnnotations) {
            if(MobileRequestParam.class.isInstance(parameterAnnotation)){
                return true;
            }
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Annotation[] parameterAnnotations = methodParameter.getParameterAnnotations();

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        for (Annotation parameterAnnotation : parameterAnnotations) {
            if(MobileRequestParam.class.isInstance(parameterAnnotation)){
                ReqVo reqVo = (ReqVo) ThreadLocalHandler.getThreadLocal("reqVo");
                log.info("服务器接收到的参数 RequestParamResolver reqvo:{}",JSONObject.toJSONString(reqVo));
                return reqVo;
            }
        }
        return null;
    }


}
